<template>
  <!-- 留言板 -->
  <div style="height: 100%">
    <div class="search" style="display: flex; margin-left: 10px">
      <el-input
        v-model="search"
        placeholder="请输入搜索内容"
        style="width: 200px"
      ></el-input
      ><el-button
        icon="el-icon-search"
        circle
        style="margin-left: 20px"
        @click="searchData(search)"
      ></el-button>
      <el-button
        icon="el-icon-plus"
        circle
        style="margin-left: 20px; color: #9bc9d3"
        @click="addInfo = true"
        v-if="identity && userAudit == 'true'"
      ></el-button>
    </div>
    <div
      class="content"
      v-loading="tableData.length <= 0"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
    >
      <el-row>
        <el-col
          :span="6"
          v-for="(item, index) in tableData"
          :key="index"
          style="padding: 10px"
          v-if="dateCompare(item)"
        >
          <el-card :body-style="{ padding: '5px' }" shadow="hover">
            <div style="display: flex">
              <img
                :src="item.messageImg"
                class="image"
                height="150px"
                width="150px"
              />
              <div style="padding: 14px; padding-right: 2px; width: 100%">
                <span> {{ item.messageTitle }} </span>
                <div class="bottom clearfix" style="position: relative">
                  <textarea v-model="item.messageDesc" class="desc" style="">
                  </textarea>
                  <el-button
                    type="text"
                    class="button"
                    @click="showDetail(item)"
                    style="position: absolute; bottom: -56px; right: 0px"
                    >查看更多</el-button
                  >
                </div>
              </div>
            </div>
            <!-- card 留言 -->
            <div style="width: 100%; margin-top: 6px">
              <el-card
                class="el-card-d"
                shadow="always"
                style="height: 186px; overflow: hidden"
              >
                <div class="infinite-list-wrapper" style="overflow: auto">
                  <el-timeline infinite-scroll-disabled="disabled">
                    <div v-if="item.allmessages.length > 0">
                      <el-timeline-item
                        v-for="(i, index) in item.allmessages.slice(0, 2)"
                        :key="index"
                        :timestamp="i.createTime"
                        placement="top"
                      >
                        <el-card class="el-card-m" style="height: 60px">
                          <p
                            style="
                              word-break: keep-all;
                              white-space: nowrap;
                              overflow: hidden;
                              text-overflow: ellipsis;
                            "
                          >
                            {{ i.memberName }}：
                            {{ i.content }}
                          </p>
                        </el-card>
                      </el-timeline-item>
                    </div>
                    <div v-else>
                      <el-timeline-item placement="top">
                        <el-card class="el-card-m" style="height: 120px">
                          <h4>还没有留言内容</h4>
                        </el-card>
                      </el-timeline-item>
                    </div>
                  </el-timeline>
                </div>
              </el-card>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <!-- 信息展示弹框 -->
      <el-dialog title="信息详情" :visible.sync="dialogFormVisible" center>
        <template>
          <div
            style="
              top: 20px;
              left: 30px;
              position: absolute;
              width: 42px;
              height: 20px;
              text-align: center;
              background: #f56c6c;
              color: white;
            "
            @click="jubao(form)"
          >
            举报
          </div>
        </template>
        <el-form :model="form" class="messageForm">
          <el-form-item label="图片" :label-width="formLabelWidth">
            <img :src="form.messageImg" alt="" height="150px" width="150px" />
          </el-form-item>
          <el-form-item label="Title" :label-width="formLabelWidth">
            <el-input
              v-model="form.messageTitle"
              autocomplete="off"
              :disabled="true"
            ></el-input>
          </el-form-item>
          <el-form-item label="相关描述" :label-width="formLabelWidth">
            <el-input
              v-model="form.messageDesc"
              autocomplete="off"
              :disabled="true"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="留言"
            :label-width="formLabelWidth"
          ></el-form-item>
          <!-- <p :key="new Date().getTime()">{{form.allmessages}}</p> -->
          <el-form-item>
            <el-card class="el-card-d" shadow="always">
              <div class="infinite-list-wrapper" style="overflow: auto">
                <el-timeline infinite-scroll-disabled="disabled">
                  <div
                    v-if="form.allmessages.length"
                    style="max-height: 400px; overflow: auto"
                  >
                    <el-timeline-item
                      v-for="(i, index) in form.allmessages"
                      :key="index"
                      :timestamp="i.createTime"
                      placement="top"
                    >
                      <el-card class="el-card-m" style="height: 60px">
                        <p
                          style="
                            word-break: keep-all;
                            white-space: nowrap;
                            overflow: hidden;
                            text-overflow: ellipsis;
                          "
                        >
                          {{ i.memberName }}：
                          {{ i.content }}
                        </p>
                      </el-card>
                    </el-timeline-item>
                  </div>
                  <div v-else>
                    <el-timeline-item placement="top">
                      <el-card class="el-card-m" style="height: 120px">
                        <h4>还没有留言内容</h4>
                      </el-card>
                    </el-timeline-item>
                  </div>
                </el-timeline>
              </div>
            </el-card>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" style="margin-top: -28px">
          <template>
            <div class="el-card-messages">
              <el-input
                type="textarea"
                :rows="4"
                placeholder="输入留言"
                maxlength="200"
                v-model="message"
              ></el-input>
              <el-button
                type="warning"
                round
                class="submit-message"
                icon="el-icon-message"
                @click="submitMessage"
                >留言</el-button
              >
              <el-button round @click="dialogFormVisible = false"
                >取 消</el-button
              >
            </div>
          </template>
        </div>
      </el-dialog>
      <!-- 信息添加弹框 -->
      <el-dialog
        title="添加信息"
        :visible.sync="addInfo"
        center
        @close="hidden"
      >
        <el-form :model="addform" ref="addForm" :rules="rules">
          <el-form-item label="图片" :label-width="formLabelWidth">
            <el-upload
              action=""
              list-type="picture-card"
              :auto-upload="false"
              :on-change="handleChange"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :limit="1"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <!-- 图片预览 -->
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-form-item>
          <el-form-item
            label="Title"
            :label-width="formLabelWidth"
            required
            prop="title"
          >
            <!--              :fetch-suggestions="queryTitleSearch" -->
            <el-autocomplete
              v-model="addform.title"
              placeholder="请输入留言主题"
              :trigger-on-focus="false"
              :fetch-suggestions="queryTitleSearch"
              @select="handleSelect"
              @keyup.enter.native="addTag(addform.title)"
              @blur="addTag(addform.title)"
              props="title"
            ></el-autocomplete>
          </el-form-item>
          <!-- <el-form-item label="出发地点" :label-width="formLabelWidth">
            <el-autocomplete
              v-model="addform.startPlace"
              :fetch-suggestions="queryPlaceSearch"
              placeholder="请输入地点"
              :trigger-on-focus="false"
              @select="handleSelect"
              @keyup.enter.native="addTag(addform.startPlace)"
              @blur="addTag(addform.startPlace)"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item label="抵达地点" :label-width="formLabelWidth">
            <el-autocomplete
              v-model="addform.endPlace"
              :fetch-suggestions="queryPlaceSearch"
              placeholder="请输入地点"
              :trigger-on-focus="false"
              @select="handleSelect"
              @keyup.enter.native="addTag(addform.endPlace)"
              @blur="addTag(addform.endPlace)"
            ></el-autocomplete>
          </el-form-item> -->
          <el-form-item label="描述" :label-width="formLabelWidth">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="有人知道美术学院张老师电话吗？"
              v-model="addform.desc"
            >
            </el-input>
          </el-form-item>
          <!-- <el-form-item label="标签" :label-width="formLabelWidth">
            <el-tag
              :key="tag"
              v-for="tag in dynamicTags"
              closable
              :disable-transitions="false"
              :type="addform.tagType"
              @close="handleClose(tag)"
              style="margin-right: 5px"
            >
              {{ tag }}
            </el-tag>
            <el-input
              class="input-new-tag"
              v-if="inputVisible"
              v-model="inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm"
            >
            </el-input>
            <el-tooltip
              class="item"
              effect="dark"
              content="标签尽可能清楚，以便查找"
              placement="top-start"
              v-else
            >
              <el-button class="button-new-tag" size="small" @click="showInput"
                >+ New Tag</el-button
              >
            </el-tooltip>
          </el-form-item> -->
          <!-- <el-form-item label="有效时间" :label-width="formLabelWidth">
            <div class="block">
              <el-date-picker
                v-model="addform.validDate"
                type="datetime"
                placeholder="选择日期时间"
                align="right"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm"
                style="width: 300px"
              >
              </el-date-picker>
            </div>
          </el-form-item>
          <el-form-item label="联系方式" :label-width="formLabelWidth">
            <el-input
              v-model="addform.contact"
              autocomplete="off"
              placeholder="请输入联系方式"
            ></el-input>
          </el-form-item> -->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addInfo = false">取 消</el-button>
          <el-button type="primary" @click="add('addForm', addform)"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </div>
    <!-- //分页动态显示 -->
    <div class="pages">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[8]"
        :page-size="8"
        layout="total, prev, pager, next, jumper"
        :total="totalData"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      // 简单留言
      message: "",
      showMessages: [
        {
          createTime: "2022-01-11 14:40",
          memberName: "扎囊三",
          content: "留言内容hhhhhhhhhhhh问问凤凰网回复回复112任务二无",
        },
        {
          createTime: "2022-12-11 14:40",
          memberName: "张三",
          content: "留言内容",
        },
      ],

      search: "",
      currentPage: 1,
      nowData: this.formatDate(new Date()),
      totalData: 0,
      // 每页内容数据
      tableData: [],
      //总数据
      tableData1: [],
      // 详细信息弹框
      dialogFormVisible: false,
      form: {
        allmessages: [],
      },
      formLabelWidth: "100px",
      // 添加信息
      addInfo: false,
      addform: {
        tagType: "warning",
        validDate: this.formatDate(new Date()),
      },
      // 图片
      dialogImageUrl: "",
      dialogVisible: false,
      // 图片列表
      fileList: [],
      loadAllTitle: [
        { value: "一卡通" },
        { value: "计算器" },
        { value: "教科书" },
        { value: "晾衣架" },
        { value: "布偶" },
        { value: "吉他" },
      ],
      loadAllPlace: [
        { value: "图书馆" },
        { value: "一期操场" },
        { value: "令雅食堂" },
        { value: "A10栋" },
        { value: "B12栋" },
        { value: "万达广场" },
      ],
      rules: {
        title: [{ required: true, message: "请输入", trigger: "blur" }],
      },
      // 新tag
      dynamicTags: [],
      inputVisible: false,
      inputValue: "",
      // 是否登录
      identity: "",
      userAudit:"",
    };
  },
  created() {
    this.getData();
    this.identity = window.sessionStorage.getItem("identity");
    this.userAudit = window.sessionStorage.getItem("userAudit");
    /*分页：
    1:0,8
    2:8,16，
    3：16,24
    // n: n-1*8 ，8n */
  },
  mounted() {},
  methods: {
    // 获取所有数据
    getData() {
      var that = this;
      axios({
        methods: "GET",
        url: "http://127.0.0.1:3000/message/messageList",
      })
        .then((res) => {
          if (res.data.code == 200) {
            // console.log(res.data.data);
            that.tableData1 = res.data.data;
          } else {
            console.log("error", res);
          }
        })
        .catch((err) => {
          console.log(err);
        });
      setTimeout(() => {
        for (let index = 0; index < that.tableData1.length; index++) {
          var messageId = that.tableData1[index].messageId;
          axios({
            methods: "GET",
            url: "http://127.0.0.1:3000/message/message",
            params: {
              messageId: messageId,
            },
          })
            .then((res) => {
              if (res.data.data) {
                that.tableData1[index].allmessages = res.data.data;
              } else {
                that.tableData1[index].allmessages = [];
              }
              // console.log(that.tableData1[index].allmessages.length, index);
            })
            .catch((err) => {
              console.log("card message", err);
            });
        }
        setTimeout(() => {
          // console.log(that.tableData1, "tableData1", that.tableData1.length);
          that.tableData = that.tableData1.slice(0, 8);
          that.totalData = that.tableData1.length;
        }, 600);
      }, 200);
    },

    // 留言信息
    submitMessage() {
      if (
        this.message == "" ||
        this.message.replace(/(^\s*)|(\s*$)/g, "") == ""
      ) {
        this.$message("要有内容才能留言哦😉");
        return;
      }
      var newMessage = {
        memberName: window.sessionStorage.getItem("userName"),
        content: this.message,
        createTime: this.nowData,
      };
      this.form.allmessages.push(newMessage);
      console.log(this.form);
      axios({
        methods: "GET",
        url: "http://127.0.0.1:3000/message/addMessage",
        params: {
          messageId: this.form.messageId,
          memberName: window.sessionStorage.getItem("userName"),
          content: this.message,
          createTime: this.nowData,
        },
      })
        .then((res) => {
          console.log(res.data.data);
          this.message = "";
        })
        .catch((err) => {
          console.log("card message", err);
          this.message = "";
        });
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.tableData = this.tableData1.slice(
        (this.currentPage - 1) * 8,
        this.currentPage * 8
      );
    },
    // 时间处理
    formatDate(date) {
      var year = date.getFullYear();
      var month = this.format(date.getMonth() + 1);
      var day = this.format(date.getDate());
      var h = this.format(date.getHours());
      var m = this.format(date.getMinutes());
      return year + "-" + month + "-" + day + " " + h + ":" + m;
    },
    format(val) {
      return Number(val) < 10 ? "0" + val : "" + val;
    },
    dateCompare(item) {
      if (item.messageAudit == 1) {
        // console.log("有效时间");
        return true;
      } else {
        for (let index = 0; index < this.tableData1.length; index++) {
          if (item.messageId == this.tableData1[index].messageId) {
            this.tableData1.splice(index, 1);
          }
        }
        this.tableData = this.tableData1.slice(0, 8);
        this.totalData = this.tableData1.length;
        return false;
      }
    },
    // 弹框
    showDetail(item) {
      if (this.identity) {
        this.dialogFormVisible = true;
        this.form = item;
        console.log(this.form, "form");
      } else {
        this.$message.error("您还未登录，无法进行该操作");
      }
    },
    // 留言信息
    takeMessage(data) {
      this.$prompt("请输入留言内容", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^(?=.*?[\u4E00-\u9FA5]){5,100}/,
        inputErrorMessage: "不能少于5个字符,必须有汉字",
      })
        .then(({ value }) => {
          data.leaveMessage = value;
          this.$message({
            type: "success",
            message: "你的留言信息是: " + value,
          });
          console.log(data);
          this.dialogFormVisible = false;
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消输入",
          });
        });
    },
    // 举报
    jubao(data) {
      this.$prompt(
        "请输入举报原因",
        "请如实填写举报，经由管理员审核后会对用户进行信息发布的限制",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputPattern: /^(?=.*?[\u4E00-\u9FA5])/,
          inputErrorMessage: "必须有汉字",
        }
      )
        .then(({ value }) => {
          data.jubao = {};
          data.jubao[window.sessionStorage.getItem("userId")] = value;
          console.log(data, "留言举报");
          axios({
            methods: "get",
            url: "http://127.0.0.1:3000/message/jubaoMessage",
            params: {
              messageId: data.messageId, //寻物id
              jubao: data.jubao[window.sessionStorage.getItem("userId")],
              userId: window.sessionStorage.getItem("userId"),
            },
          })
            .then((res) => {
              if (res.data.code == 200) {
                this.$message({
                  type: "success",
                  message: "已收到你的举报信息 ",
                });
              } else {
                this.$message.error("消息提交失败，请再次尝试");
              }
            })
            .catch((err) => {
              console.log(err);
            });
          console.log(data);
          this.dialogFormVisible = false;
             window.location.reload();
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消输入'
          // });
        });
    },
    // add
    // 图片
    handleChange(file, fileList) {
      console.log(file, fileList);
      for (let i = 0; i < fileList.length; i++) {
        fetch(fileList[i].url)
          .then((data) => {
            const blob = data.blob();
            console.log(blob);
            return blob;
          })
          .then((blob) => {
            let reader = new window.FileReader();
            reader.onloadend = function () {
              const data = reader.result;
              fileList[i].url = data;
            };
            reader.readAsDataURL(blob);
          });
      }
      var img = [];
      setTimeout(() => {
        for (let index = 0; index < fileList.length; index++) {
          img.push(fileList[index].url);
        }
        console.log(img);
      }, 300);

      this.fileList = img;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      console.log(file);
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    queryTitleSearch(queryString, cb) {
      var restaurants = this.loadAllTitle;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    queryPlaceSearch(queryString, cb) {
      var restaurants = this.loadAllPlace;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    handleSelect(item) {
      console.log(item);
      // this.addTag(item.value);
    },
    hidden() {
      //处理close
      this.addInfo = false;
      (this.addform = {
        tagType: "danger",
        validDate: this.formatDate(new Date()),
      }),
        (this.dynamicTags = []);
      this.inputValue = "";
    },
    add(formName, item) {
      console.log(item);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log("submit!");
          item.img = this.fileList;
          axios
            .post("http://127.0.0.1:3000/message/addMessage", {
              InfoPublisher: window.sessionStorage.getItem("userName"),
              messageDesc: item.desc,
              messageImg: item.img[0],
              messageTitle: item.title,
            })
            .then((data) => {
              console.log(data);
              this.getData();
            })
            .catch((err) => {
              console.log(err);
              this.$message.error("图片过大，请再次尝试");
            });
          this.addInfo = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 新tag
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },
    addTag(value) {
      console.log(value);
      let inputValue = value;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    // 搜索前端实现
    searchData(data) {
      let list = this.tableData1.filter((item, index) =>
        item.messageTitle.includes(data)
      );
      this.tableData1 = list;
      this.tableData = tableData1.slice(0, 8);
      this.totalData = tableData1.length;
    },
  },
};
</script>

<style scoped lang="css">
/* 显示留言 */
.el-timeline-item {
  padding-bottom: 0px;
}
.el-card-d :first-child {
  padding: 1px;
}
.el-card-m :first-child {
  padding: 7px;
}
.messageForm .el-form-item {
  margin-bottom: 8px;
}
.el-card-messages .el-button {
  margin-top: 5px;
}
.desc {
  overflow-y: hidden;
  height: 45px;
  font-size: 13px;
  color: #999;
  width: 100%;
  border: none;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
  resize: none;
}
.time {
  display: block;
  padding-top: 8px;
  font-size: 13px;
  color: #999;
}
.bottom {
  margin-top: 8px;
  line-height: 12px;
}

.button {
  padding: 0;
  float: right;
}

.image {
  /* width: 100%; */
  display: block;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}
.tags {
  margin-top: 8px;
}
.tags .el-tag {
  margin: 3px;
}
/* .el-card {
  height: 370px;
} */
.pages {
  position: fixed;
  bottom: 10px;
  right: 10px;
}
/* 新tag */
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
/* 举报样式 */
.el-message-box__title {
  color: red !important;
  font-size: 9px !important;
}
</style>